import { Component, OnInit } from '@angular/core';
import { SellCouponbagHandleService } from './sell-couponbag-handle.service';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';

@Component({
  selector: 'app-sell-couponbag-handle',
  templateUrl: './sell-couponbag-handle.component.html',
  styleUrls: ['./sell-couponbag-handle.component.scss'],
  providers: [DatePipe]
})
export class SellCouponbagHandleComponent implements OnInit {

  // 路由传参
  routeForms: any ={
    mode: 0 // 0：新增,1：编辑,2：查看,3：复制
  };
  // formDatas
  formDatas: any = {
    name: '', // 名称
    state: '', // 状态 0启用 1禁用
    remark: '', // 备注
    number: '', // 关联数量
    couponIdList: [] // 对应优惠券JSONOList --- tableData
  }
  submitLoading = false;

  // modelTable
  isVisible: boolean = false;
  modelSeachForms: any = {
    source: '',
    name: ''
  }
  modelTableData: any = [];
  modelTableForms: any = {
    tableLoading: false,
    pageNum: 1,
    pageSize: 10,
    total: 0
  };

  /**
   * 勾选 modelTable
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = []; // 当前展示页面数据
  setOfCheckedId = new Set<number>(); // 已选ids
  setofCheckedArrs: any[] = []; // 已选项数组

  // 业务options 1：配件 2：二手 3：加价 4：定制
  businessOptions: any = [
    {value: 1, label: '配件'},
    {value: 2, label: '二手'},
    {value: 3, label: '加价'},
    {value: 4, label: '定制'}
  ];
  addCouponType: number = 1;

  /**
   * ----------------------------------------------------------------
   * 勾选设置 Table
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean, item?: any): void {
    if (checked) {
      this.setOfCheckedId.add(id);

      if (this.setofCheckedArrs.length > 0) {
        let isHas = this.setofCheckedArrs.some((tag: any) => { return tag.id === id });
        if (!isHas) {
          this.setofCheckedArrs.push({...item, packType: this.addCouponType});
        }
      } else {
        this.setofCheckedArrs.push({...item, packType: this.addCouponType});
      }
    } else {
      this.setOfCheckedId.delete(id);

      let delIndex = this.setofCheckedArrs.findIndex((tag: any) => { return tag.id === id });
      this.setofCheckedArrs.splice(delIndex, 1);
    }
  }
  // 单选
  onItemChecked(id: number, checked: boolean, item?: any): void {
    this.updateCheckedSet(id, checked, item);
    this.refreshCheckedStatus();
  }
  // 全选
  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value, item));
    this.refreshCheckedStatus();
  }
  // 当前页面展示数据改变的回调函数
  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }
  // 全选按钮状态
  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private service: SellCouponbagHandleService
  ) {
    this.activatedRoute.queryParams.subscribe((res: any) => {
      this.routeForms = res;
    })
  }

  ngOnInit(): void {
    if (this.routeForms.mode != 0) {
      this.loadCouponDetailData()
    }
  }

  // 查询优惠券卡包详情
  async loadCouponDetailData() {
    let params = {
      id: this.routeForms.id
    }
    const res: any = await this.service.queryCouponDetailData(params);

    if (res.code === 0) {
      const { couponInfoVOList, couponPackage } = res.data
      
      this.formDatas.name = couponPackage.name || '';
      this.formDatas.state = String(couponPackage.state) || '';
      this.formDatas.remark = couponPackage.remark || '';
      this.formDatas.number = couponPackage.number || '';
      this.formDatas.couponIdList = couponInfoVOList || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 查询优惠券列表(model)
  async couponTableData() {
    const params = {
      ...this.modelSeachForms,
      source: "1", // 优惠券包(值为任意),不传为优惠券
      pageNum: this.modelTableForms.pageNum,
      pageSize: this.modelTableForms.pageSize
    }

    this.modelTableForms.tableLoading = true;
    const res: any = await this.service.getCouponTableData(params, this.addCouponType);
    this.modelTableForms.tableLoading = false;

    if (res.code === 0) {
      const { records, total }: any = res.data || [];

      this.modelTableData = records || [];
      this.modelTableForms.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 保存 ** 编辑
   * mode 0：新增,1：编辑,2：查看,3：复制
   * @returns 
   */
  async subFormData() {
    if (!this.verifData()) {
      return
    }
    // 处理已关联数据
    let couponIdArrs = [];
    if (this.formDatas.couponIdList.length) {
      couponIdArrs = this.formDatas.couponIdList.map((item: any) => {
        return {
          id: item.id,
          packType: item.packType,
          relationNumber: item.relationNumber
        }
      })
    }

    let params = {
      ...this.formDatas,
      couponIdList: couponIdArrs
    }
    if (['1'].includes(this.routeForms.mode)) {
      params.id = this.routeForms.id
    }

    this.submitLoading = true;
    let res: any;
    if (['0', '3'].includes(this.routeForms.mode)) {
      res = await this.service.addCouponData(params);
    } else {
      res = await this.service.editCouponData(params);
    }
    this.submitLoading = false;

    if (res.code === 0) {
      this.message.success('操作成功');
      this.router.navigate(['/sell/couponbagManage']);
    } else {
      this.message.error(res.message);
    }
  }

  // 删除关联项
  deleteItems(index: number) {
    // this.formDatas.couponIdList.splice(index, 1);
    this.formDatas.couponIdList = this.formDatas.couponIdList.filter((d: any, i: number) => i !== index);
  }

  // 打开model弹窗(赋值)
  addTableItems(type: number) {
    this.addCouponType = type;
    this.setOfCheckedId.clear();
    
    let modalArrs = this.formDatas.couponIdList.filter((item: any) => item.packType === type);
    modalArrs.forEach((ele: any) => {
      this.setOfCheckedId.add(ele.id);
    });
    this.setofCheckedArrs = JSON.parse(JSON.stringify(modalArrs));

    this.modelTableForms.pageNum = 1;
    this.couponTableData()
    this.isVisible = true;
  }
  // model确定
  handleOk(): void {
    this.isVisible = false;
  }
  // model取消
  handleCancel(): void {
    this.isVisible = false;

    this.setOfCheckedId.clear();
    this.setofCheckedArrs = [];
  }

  // model搜索
  seachData() {
    this.modelTableForms.pageNum = 1;
    this.couponTableData()
  }

  resetData() {
    this.modelSeachForms.name = '';
    this.modelTableForms.pageNum = 1;
    this.couponTableData()
  }

  // 关联已选商品
  relationData() {
    if (this.setOfCheckedId.size <= 0) {
      this.message.warning('请先选择商品');
      return
    }

    let listArrs = this.formDatas.couponIdList.filter((item: any) => item.packType !== this.addCouponType);
    this.formDatas.couponIdList = [...listArrs, ...this.setofCheckedArrs];
    this.isVisible = false;
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.modelTableForms.pageNum = index;
    this.couponTableData()
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.modelTableForms.pageNum = 1;
    this.modelTableForms.pageSize = sizeNum;

    this.couponTableData()
  }

  /**
   * 状态转文字
   * @param status 
   */
  status_To_text(status: any) {
    let text = "";
    switch (status) {
      case 1:
        text = "审核通过";
        break;
      case 2:
        text = "进行中";
        break;
      case 3:
        text = "已结束";
        break;
      case 4:
        text = "已停止";
        break;
      case 5:
        text = "草稿";
        break;
      case 6:
        text = "待审核";
        break;
      case 7:
        text = "审核不通过";
        break;
      default:
        text = "---";
        break;
    }
    return text;
  }

  businessFilter(type: number) {
    let tempObj: any = this.businessOptions.find((item: any) => item.value === type);
    return tempObj?.label || '配件';
  }

  // 验证
  verifData() {
    if (!this.formDatas.name) {
      this.message.warning('请输入券包名称');
      return false;
    } else if (!this.formDatas.state) {
      this.message.warning('请选择状态');
      return false;
    } else if (!this.formDatas.remark) {
      this.message.warning('请输入备注');
      return false;
    } else {
      return true;
    }
  }
}
